package quick.start.ui.dialog;

import java.util.LinkedList;
import java.util.List;

import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;

public class SimpleDialogFragment extends DialogFragment {

    private OnDismissListenable mOnDismissListenable = new OnDismissListenable();
    private OnShowListenable    mOnShowListenable    = new OnShowListenable();

    public void registerOnDismissListener(OnDismissListener listener) {
        mOnDismissListenable.addListener(listener);
    }

    public void unregisterOnDismissListener(OnDismissListener listener) {
        mOnDismissListenable.removeListener(listener);
    }

    public void registerOnShowListener(OnShowListener listener) {
        mOnShowListenable.addListener(listener);
    }

    public void unregisterOnShowListener(OnShowListener listener) {
        mOnShowListenable.removeListener(listener);
    }
    
    @Override
    public void onDismiss(DialogInterface dialog) {
        super.onDismiss(dialog);
        mOnDismissListenable.onDismiss(dialog);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mOnShowListenable.onShow(getDialog());
    }
    
    public static interface OnShowListener {
        /**
         * This method will be invoked when the dialog is shown.
         *
         * @param dialog The dialog that was shown will be passed into the
         *            method.
         */
        public void onShow(DialogInterface dialog);
    }
    
    private static class OnDismissListenable implements OnDismissListener{
        private List<OnDismissListener> listeners = new LinkedList<OnDismissListener>();

        @Override
        public void onDismiss(DialogInterface dialog) {
            for (OnDismissListener listener : listeners) {
                listener.onDismiss(dialog);
            }
        }

        public void addListener(OnDismissListener listener) {
            listeners.add(listener);
        }

        public void removeListener(OnDismissListener listener) {
            listeners.remove(listener);
        }
    }
    
    private static class OnShowListenable implements DialogInterface.OnShowListener{
        private List<OnShowListener> listeners = new LinkedList<OnShowListener>();

        @Override
        public void onShow(DialogInterface dialog) {
            for (OnShowListener listener : listeners) {
                listener.onShow(dialog);
            }
        }

        public void addListener(OnShowListener listener) {
            listeners.add(listener);
        }

        public void removeListener(OnShowListener listener) {
            listeners.remove(listener);
        }
    }
}
